package cn.wizzer.app.crown.commons.util;

import cn.wizzer.app.crown.modules.models.CrownConfig;
import cn.wizzer.app.crown.modules.models.constant.CrownConstant;
import cn.wizzer.app.crown.modules.models.constant.CrownPattern;
import cn.wizzer.app.crown.modules.models.constant.CrownRedisConstant;
import cn.wizzer.framework.util.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.io.IOException;
import java.util.regex.Matcher;

import static cn.wizzer.framework.util.HttpUtil.createMap;

/**
 * 皇冠发送http请求工具。
 */
public class CrownHttpUtil {
    private static final Log log = Logs.get();

    @Inject
    private static RedisService redisService;



    public static void setRedisService(RedisService redisService) {
        CrownHttpUtil.redisService = redisService;
    }
    /**
     * 出现异常重试3次。如果获取到新的皇冠地址，自动去请求。
     * 请求成功返回数据body，失败返回空字符串
     *
     * @param tailUrl
     * @param config
     * @return
     */
    public static String createGet(String tailUrl, CrownConfig config, int reTry) {
        String body = "";
        // 把皇冠地址拼接到url头部
        String url = config.getRealSite() + tailUrl;
        try {
            body = HttpUtil.createRequest()
                    .setUrl(url)
                    .setHeader(createMap("cookie", config.getCookie()))
                    .setTimeOut(5000)
                    .send(HttpUtil.HTTP_METHOD.GET)
                    .getBody();
            // 检测新地址
            if (getNewDomain(body, config)) {
                reTry = CrownConstant.RE_TRY_TIMES;
                return createGet(tailUrl, config, --reTry);
            }
        } catch (IOException e) {
            log.error("爬取数据失败，URL：" + url + "重试次数剩余：" + reTry);
            log.error("异常具体信息：" + e);
            if (reTry > 1) {
                return createGet(tailUrl, config, --reTry);
            }
        }
        return body;
    }


    /**
     * @param tailUrl
     * @param config
     * @param reTry
     * @return
     */
    public static String loginCrown(String tailUrl, CrownConfig config, int reTry) {
        String body = "";
        // 把皇冠地址拼接到url头部
        String url = config.getRealSite() + tailUrl;
        try {
            HttpUtil.Response res = HttpUtil.createRequest()
                    .setUrl(url)
                    .setTimeOut(5000)
                    .setParam(createMap(
                            "username", config.getUsername(),
                            "passwords", config.getPasswords(),
                            "langx", CrownConstant.LANGX,
                            "auto", "DADBDE",
                            "blackbox", "04003ZWEKk/A6R4pIfq2LLtL/Y0ii/xnum/zfPpuNJz0@2UCP3I/gtJSIOMr0YV5w5CL23AfbTn4cXXp/GQAAQUiaUEFfeFxZ4mShd01Jpb3ubmMzJtSWnIRBcEv6aX0T5Ew5sdrzcINkHqSqiU/wlowqKhMe4b9SwNjI/GgQmgZKntdzAoqCedUsdECyaln3bcDds/15Sn7/vmnHbzmopDdqilCz8QbOZkv6m6klcyz3h9sZFkfTsFfRirgS3ww3o6oa0Yy5JnHYpPbcB9tOfhxden8ZAABBSJpQQV94XFniZKF3TUmlve5uYzMm1JachEFwS/ppfRPkTDAqvQx/6iBZqmv4an1VB05SuO@gWkTCwWmUGFXcIY@JCCsEfnG/KSZA2uWbNuqgNN0ic5Zo9xviVx@4oTf94nSHOzjyi9frDdHtjbiPupS5MgwJY/1kvy4dZTG3Q1JuSFJp5PUg5jUaSdzBR@/B5fnRVjCPy8LXfsXNXdgvFjjoIbCmzQNSG7Ks9NGSaOBqmcYK91lVuo9zUJXs9LG5o/h3EmQjk2mIgfaCnACZwym27Yc/4DNEoi/Znv4Scx8Lgvp38ec2SH8oDeShPod2qf1@Lx@m25PhX7nsueaw/fwdi38MA3Wh1WoJgVSk0pcKUTCDJsS50gPlqoMQcHHQxqCfY9jE3aBXTo@WO5tA7Jn6V3EY0bKFRRRi6gqYs3uxZxycMHZCcHjpabC3SvgKdF2CjlU0y9oNd@sjcxpJiuDOyEioquMr6B3kRssV7u80BzgiEms7PTw/N/7HinDpb16xsYSmrsKhFi8VDdLGBfK9PH/LgnAtMTg3G/gqjChOr22Liq0dKm2qxC/CwsbD4fITMj6Y82LrlflYU9iUMb03X6mAJ3ZTHu23WaFMcpDuPKpNYuU/h@Gc0nbtw2dg9JBSzKz6zFbyZbyxPMQMv7YZ9mxtLKX2QfncSs2NHNZ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SYstKbZ0Ftu@kBWF7xgv6M"
                    ))
                    .send(HttpUtil.HTTP_METHOD.POST);
            // 如果是404直接设置维护
            int code = res.getStatusLine().getStatusCode();
            if (404 == code || 500 == code) {
                return body;
            }

            // 检测新地址
            if (getNewDomain(body, config)) {
                reTry = CrownConstant.RE_TRY_TIMES;
                return loginCrown(tailUrl, config, --reTry);
            }

        } catch (IOException e) {
            log.error("爬取数据失败，URL：" + url + "重试次数剩余：" + reTry);
            log.error("异常具体信息：" + e);
            if (reTry > 1) {
                return loginCrown(tailUrl, config, --reTry);
            }
        }
        return body;
    }


    /**
     * 获取新地址
     *
     * @param body
     * @param config
     * @return
     */
    private static boolean getNewDomain(String body, CrownConfig config) {
        if (body.contains("newdomain")) {
            Matcher m = CrownPattern.NEW_DOMAIN.matcher(body);
            if (m.find()) {
                String newDomain = m.group(0).replace("action='", "").replace("'", "");
                config.setRealSite(newDomain);
                redisService.set(CrownRedisConstant.CROWN_ACCOUNT + config.getUsername(), JSONObject.toJSONString(config));
                log.error("获取到新地址：" + newDomain);
                return true;
            } else {
                log.error("获取不到newdomain，body：" + body);
            }
        }
        return false;
    }
}
